package com.javacoo.xservice.base.utils;

import java.util.Optional;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 * <li></li>
 *
 * @author: duanyong@jccfc.com
 * @since: 2021/3/12 17:30
 */
@Component
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> type) {
        try {
            return Optional.ofNullable(applicationContext).orElseThrow(() -> new IllegalStateException("non in spring application context.")).getBean(type);
        } catch (Exception e) {
            return null;
        }
    }
    public static <T> T getBean(String name,Class<T> type) {
        try {
            return Optional.ofNullable(applicationContext).orElseThrow(() -> new IllegalStateException("non in spring application context.")).getBean(name,type);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void registerBean(String beanName,Object object){
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;

        configurableApplicationContext.getBeanFactory().registerSingleton(beanName, object);
    }
}
